<template>
  <div class="services-list">
    <el-card shadow="never">
      <template #header>
        <div class="page-header">
          <h2>服务项目管理</h2>
          <el-button type="primary" @click="handleAdd" v-if="authStore.userRole !== '用户'">
            <el-icon><Plus /></el-icon>
            添加服务
          </el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="queryForm" inline class="search-form">
        <el-form-item label="服务名称">
          <el-input v-model="queryForm.serviceName" placeholder="请输入服务名称" clearable />
        </el-form-item>
        <el-form-item label="适用宠物类型">
          <el-select v-model="queryForm.applicablePetType" placeholder="请选择宠物类型" clearable style="width: 200px;">
            <el-option label="猫" value="猫" />
            <el-option label="狗" value="狗" />
            <el-option label="通用" value="通用" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
      >
        <el-table-column label="序号" width="80">
          <template #default="{ $index }">
            {{ (pagination.current - 1) * pagination.size + $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="serviceName" label="服务名称" width="200" />
        <el-table-column prop="serviceDescription" label="服务描述" min-width="250" show-overflow-tooltip />
        <el-table-column prop="durationMinutes" label="标准时长(分钟)" width="150" />
        <el-table-column prop="servicePrice" label="价格(元)" width="120" />
        <el-table-column prop="applicablePetType" label="适用宠物类型" width="150" />
        <el-table-column label="操作" width="180" fixed="right" v-if="authStore.userRole !== '用户'">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { servicesApi } from '@/api'
import type { Services, ServicesQuery } from '@/types'
import { handlePageResponse } from '@/utils/pagination'

const router = useRouter()
const authStore = useAuthStore()

// 查询表单
const queryForm = reactive<Omit<ServicesQuery, 'pageNum' | 'pageSize'>>({
  serviceName: '',
  applicablePetType: ''
})

// 表格数据
const tableData = ref<Services[]>([])
const loading = ref(false)

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const params: ServicesQuery = {
      pageNum: pagination.current,
      pageSize: pagination.size,
      ...queryForm
    }
    const response = await servicesApi.getPage(params)
    const pageData = handlePageResponse<Services>(response)
    
    // 移除兼容性处理，直接使用返回数据
    tableData.value = pageData.records
    pagination.total = pageData.total
  } catch (error) {
    console.error('获取服务项目列表失败:', error)
    ElMessage.error('获取服务项目列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(queryForm, {
    serviceName: '',
    applicablePetType: ''
  });
  pagination.current = 1;
  fetchData();
}

// 添加
const handleAdd = () => {
  router.push('/services/add')
}

// 编辑
const handleEdit = (row: Services) => {
  router.push(`/services/update/${row.serviceId}`)
}

// 删除
const handleDelete = async (row: Services) => {
  try {
    await ElMessageBox.confirm(`确定要删除服务"${row.serviceName}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await servicesApi.delete(row.serviceId!)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  fetchData()
}

// 当前页改变
const handleCurrentChange = (current: number) => {
  pagination.current = current
  fetchData()
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.services-list {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 